<?php
namespace App\Http\Controllers\Alipay;

use App\Models\GoodsCustomRent;
use App\Models\GoodsSpec;
use App\Models\MemberOther;
use App\Models\Order;
use App\Models\OrderLease;
use App\Services\AlipayService;
use App\Services\AntchainAtoService;
use App\Services\AntchainService;
use App\Services\CommonService;
use App\Services\EsignService;
use App\Services\GoodsService;
use App\Services\NotarizeService;
use Illuminate\Http\Request;

// class AntchainController extends BaseController
class AntchainController
{
    /**
     * 智能合同
     */
    public function createAntchain(Request $request)
    {
        $order_id = $request->input('order_id');
        if (!empty($order_id)) {
            $order = Order::from('sp_order_2 as o')->where('o.id', $order_id)
                ->leftjoin('sp_order_credit as c', 'c.order_id', 'o.id')
                ->leftjoin('sp_member_2 as u', 'o.uid', 'u.id')
                ->leftjoin('sp_shop_user_2 as su', 'o.seller_id', 'su.member_id')
                ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                ->leftjoin('sp_goods_2 as g', 'og.goods_id', 'g.id')
                ->select(
                    'o.id', 'o.mini_id', 'o.trade_no', 'o.begin_time', 'o.zulinbao_order_id', 'o.end_time', 'o.pact_url_3', 'o.uid', 'o.seller_id', 'o.is_insurance_choose',
                    'o.flow_id', 'o.mobile', 'o.user_email', 'o.sign_num', 'o.address', 'o.rent_total', 'o.month_total', 'o.amount', 'o.realname', 'o.rent_total',
                    'o.foregift', 'o.status', 'o.prov', 'o.city', 'o.area', 'o.sign_status', 'o.is_rent_choose'
                    , 'c.platformLoanNo', 'o.create_time','og.cash_pledge','u.idcard_front','u.idcard_back','og.goods_name'
                    , 'u.ant_user_id', 'u.mobile as user_mobile', 'u.id as x_user_id', 'u.cert_name', 'u.user_id', 'u.cert_no', 'u.esign_user_id'
                    , 'u.idcard_front', 'u.idcard_back', 'og.id as order_goods_id ', 'og.pact_type', 'og.is_buy_out', 'og.goods_title', 'og.setmeal_title',
                    'og.lease_set', 'og.setmeal_price', 'og.setmeal_foregift', 'o.prepayment_total', 'o.pact_url',
                    'og.goods_id', 'og.setmeal_id', 'og.id as order_goods_id', 'og.spec_id', 'og.lease_price', 'og.lease_time', 'og.website_price', 'og.start_date'
                    , 'su.mechanism', 'su.faname', 'su.shopname', 'su.contact_tel', 'su.company', 'su.company_area', 'su.companyid', 'su.id as shop_user_id'
                    , 'su.ant_user_id as mer_ant_id', 'o.sign_no',  'su.ant_seal_id'
                    , 'g.new_grade')
                ->first();
            $order = $order ? $order->toArray() : [];

            if (!empty($order)) {

                if (!$order['cert_no'] || !$order['cert_name']) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未实名认证');
                }
//                if (!$order['idcard_front'] || !$order['idcard_back']) {
//                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '身份证照片未上传');
//                }
                if ($order['sign_status'] != 2) {
                    Order::where('id', $order_id)->update(['sign_status' => EsignService::ESIGN_STATUS_SIGNING]);
                }

                if (!empty($order['flow_id'])) {
                    $signStatus = AntchainAtoService::querySignFlow($order['sign_no']);
                    if (isset($signStatus['status']) && $signStatus['status'] == 'DRAFT') {
                        $data['flowId'] = $order['flow_id'];
                        $data['signerId'] = $order['esign_user_id'];
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '草稿！重新发起签署', $data);
                    }
                    if (isset($signStatus['status']) && $signStatus['status'] == 'SIGNING') {
                        $data['flowId'] = $order['flow_id'];
                        $data['signerId'] = $order['esign_user_id'];
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '合同签署中，请勿重复发起', $data);
                    }
                    if (isset($signStatus['status']) && $signStatus['status'] == 'FINISH') {
                        $res = $signStatus;
                        $docList = json_decode($res['docList'], true);
                        if ($res['resultCode'] == 'OK' && $res['status'] == 'FINISH') {
                            $fileUrl = $docList[0]['downloadUrl'];
                            $fileName = $res['flowId'] . ".pdf";
                            $file = file_get_contents($fileUrl);
                            $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/storage/tmp/' . $fileName;

                            file_put_contents($path, $file);
                            $uploud_res = AlipayService::upload($fileName, $path);
                            if ($uploud_res['status']) {
                                if (file_exists($path)) {
                                    unlink($path);
                                }
                            }
                            $order_data['sign_no'] = $res['signNo'];
                            $order_data['pact_url'] = $fileName;
                            $order_data['sign_status'] = EsignService::ESIGN_STATUS_FINISH;
                            Order::where('id', $order['id'])->update($order_data);
                            $order['pact_url'] = $fileName;
//                            NotarizeService::uploadOrderInfo($order);

                            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署已完成');
                        }
                    }
                }

                $result = AntchainAtoService::submitBehindSignFlow($order);
                if (!empty($result['resultCode']) && $result['resultCode'] == 'OK') {
                    $flowId = $result['flowId'];
                    $signNo = $result['signNo'];
                    $esign_user_id = $result['accountId'];
                    MemberOther::where('id', $order['uid'])->update(['esign_user_id' => $esign_user_id]);
                    $signInfo = json_decode($result['signInfo'], true);
                    $res = Order::where('id', $order_id)->update(['flow_id' => $flowId, 'sign_no' => $signNo, 'sign_url' => $signInfo['shortUrl'], 'sign_status' => EsignService::ESIGN_STATUS_SIGNING]);
                    if ($res) {
                        $data['flowId'] = $flowId;
                        $data['signerId'] = $esign_user_id;
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '合同发起成功', $data);
                    } else {
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署信息记录失败');
                    }
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同创建失败，请联系客服');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
//        $order_id = $request->input('order_id');
//        if(!empty($order_id)){
//            $order = Order::where('id',$order_id)->select('sign_url','sign_status')->first();
//            $order = obToArray($order);
//            if($order['sign_status'] == EsignService::ESIGN_STATUS_FINISH){
//
//                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同已签署成功，请勿重复操作');
//            }else{
//
//                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'合同发起成功',['sign_url'=>$order['sign_url']]);
//            }
    }

}
